package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Set;

@Component//对象的创建权交给Spring,
public class SpringSecurityUserService implements UserDetailsService {
    //通过网络查询对应的服务，如果想要引入该服务，必须使用dubbo的包扫描
    @Reference
    private UserService userService;

    /**
     * 根据用户录入的用户名查询user对象
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);//用户--》角色--》权限
        if (user == null) {
            //没有该用户信息
            return null;
        }
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        //返回一个用户对象(spring security 内的)
        Set<Role> roles = user.getRoles();
        //授予角色
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return securityUser;
    }
}
